package com.lagou.api;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class UpdateNodeData implements Watcher {

    private static ZooKeeper zooKeeper;

    /**
     * 创建会话
     *
     * @param args
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        /*
             客户端可以通过创建一个zk实例来连接zk服务器
             new Zookeeper(connectString,sesssionTimeOut,Wather)
             connectString: 连接地址:IP:端口
             sesssionTimeOut:会话超时时间:单位毫秒
             Wather:监听器(当特定事件触发监听时，zk会通过watcher通知到客户端)
         */
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new UpdateNodeData());
        //线程等待
        Thread.sleep(Integer.MAX_VALUE);
    }

    //当前类实现了Watcher接口，重写了process方法，该方法负责处理来自Zookeeper服务端的 watcher通知，
    // 在收到服务端发送过来的SyncConnected事件之后，解除主程序在CountDownLatch上 的等待阻塞，至此，会话创建完毕
    @Override
    public void process(WatchedEvent watchedEvent) {

        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("执行了process方法");
            try {
                //修改节点信息
                updateNodeData();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (KeeperException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 修改节点信息
     */
    private void updateNodeData() throws InterruptedException, KeeperException {
        byte[] data = zooKeeper.getData("/la_persistent", false, null);
        System.out.println("修改前的数据：" + new String(data, StandardCharsets.UTF_8));

        Stat stat = zooKeeper.setData("/la_persistent", "修改持久节点的内容".getBytes(StandardCharsets.UTF_8), -1);
        System.out.println("修改的状态：" + stat);

        byte[] afterData = zooKeeper.getData("/la_persistent", false, null);
        System.out.println("修改后的数据：" + new String(afterData, StandardCharsets.UTF_8));
    }
}
